package com.example.demo.system.controller;

import com.example.demo.common.R;
import com.example.demo.system.entity.FItem;
import com.example.demo.system.service.impl.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Comparator;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FileService fileService;
    // 不分片
    @PostMapping("upload")
    public R upload(MultipartFile file, String path) {
        fileService.save(file,path);
        return R.okShow("ok");
    }

    @PostMapping("uploadSlice")
    public R uploadSlice(MultipartFile blob,String sliceFileName) {
        fileService.cacheSlice(blob,sliceFileName);
        return R.ok();
    }

    @GetMapping("coalesce")
    public R coalesce( @RequestParam String path,
                       @RequestParam String sliceFileName,
                       @RequestParam String fileName,
                       @RequestParam int sliceTotalNumber) {
        fileService.coalesce(path,sliceFileName,fileName,sliceTotalNumber);
        return R.okShow("ok");
    }

    @GetMapping("abort")
    public R abort( @RequestParam String sliceFileName,@RequestParam Integer uploadedSlice) {
        fileService.abort(sliceFileName,uploadedSlice);
        return R.okShow("取消了😍");
    }


    @GetMapping("mkdir")
    public R mkdir(@RequestParam String dirName,@RequestParam String path) {
        fileService.mkdir(dirName,path);
        return R.okShow("ok");
    }

    @GetMapping("rename")
    public R rename(@RequestParam String oldName,
                    @RequestParam String newName,
                    @RequestParam String path) {
        fileService.rename(oldName,newName,path);
        return R.okShow("ok");
    }

    @GetMapping("mv")
    public R mv(@RequestParam String from,
                    @RequestParam String to,
                    @RequestParam String path) {
        fileService.mv(from,to,path);
        return R.okShow("ok");
    }



    @GetMapping("getCurrentItems")
    public R getCurrentItems(@RequestParam(required = false) String path) {
       List<FItem> list =  fileService.getCurrentItems(path);
       list.sort((o1, o2) -> {
           if (o1.isFolderFlag() && !o2.isFolderFlag()){
               return -1;
           }else if ((o1.isFolderFlag() && o2.isFolderFlag()) ||
                   (!o1.isFolderFlag() && !o2.isFolderFlag())
           ){
               return 0;
           }else if(!o1.isFolderFlag() && o2.isFolderFlag()){
               return 1;
           }
           return 0;
       });
        try {
            log.info("模拟长时间加载～");
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return R.ok(list);
    }
}
